package com.tech.middle_ware.h2;

import cn.hutool.core.map.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.h2.server.web.WebServlet;
import org.h2.tools.Server;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import java.sql.SQLException;

@Slf4j
public class SpringBootH2Server {

    @Bean//启动webServer
    public ServletRegistrationBean<WebServlet> registH2WebServlet() {
        ServletRegistrationBean<WebServlet> srb = new ServletRegistrationBean<>(new WebServlet());
        srb.setInitParameters(MapUtil.builder("-webAllowOthers", "")
                .put("-trace", "")
                .put("-browser", "")
                .build());
        srb.addUrlMappings("/h2console/*");
        return srb;
    }

    @Bean(name="tcpServer",initMethod="start",destroyMethod="stop")
    @ConditionalOnExpression("${h2.enableAppServer:true}==true")
    @Value("${h2.serverConfig:}")
    public Server tcpServer(String[] configs) throws SQLException {
        Server server = Server.createTcpServer(configs);
        System.out.println(server.getURL());
        return server;
    }
}

